<template>
  <div id="mapContainer" class="map-container">
    <div
        v-show="showTooltip"
        class="custom-tooltip"
        :style="tooltipStyle"
    >
      <div class="tooltip-content">
        <div class="remarks">{{ tooltipContent.remarks }}</div>
        <div class="timestamp">{{ tooltipContent.timeStamp }}</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, watch, nextTick } from 'vue';
import AMapLoader from '@amap/amap-jsapi-loader';

const props = defineProps({
  logisticInfo: {
    type: Array,
    required: true,
    validator: (value) => value.every(item =>
        'location' in item &&
        'remarks' in item &&
        'timeStamp' in item
    )
  }
});

const map = ref(null);
const markers = ref([]);
const showTooltip = ref(false);
const tooltipContent = ref({ remarks: '', timeStamp: '' });
const tooltipStyle = ref({ left: '0px', top: '0px' });
let geocoder = null;

const iconConfig = {
  start: {
    url: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png',
    size: [19, 31]
  },
  end: {
    url: 'https://webapi.amap.com/theme/v1.3/markers/n/end.png',
    size: [19, 31]
  },
  car: {
    url:  'https://a.amap.com/jsapi_demos/static/demo-center/icons/car.png', // 确保这个 URL 是有效的
    size: [26, 52]
  },
  default: {
    url: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
    size: [19, 31]
  }
};

const clearResources = () => {
  markers.value.forEach(marker => marker.setMap(null));
  markers.value = [];
  if (map.value) {
    map.value.destroy();
    map.value = null;
  }
};

const initializeMap = async () => {
  window._AMapSecurityConfig = {
    securityJsCode: "4cb512290cb2f2cde33ae3284c6b8073",
  };

  try {
    const AMap = await AMapLoader.load({
      key: "48dff654e078158ff016c701f2755ddf",
      version: "2.0",
      plugins: ["AMap.Geocoder", "AMap.Driving"]
    });

    clearResources();

    map.value = new AMap.Map("mapContainer", {
      viewMode: "3D",
      zoom: 12,
      center: [116.397428, 39.90923],
    });

    geocoder = new AMap.Geocoder();

    await processWaypoints(AMap);
    await createMarkers(AMap);
    focusOnCurrentPosition();

  } catch (error) {
    console.error('地图初始化失败:', error);
  }
};

const processWaypoints = async (AMap) => {
  const validPoints = props.logisticInfo
      .slice(0, -1) // 排除最后一个点（当前位置）
      .filter(item => item.longitude && item.latitude);

  if (validPoints.length < 2) return;

  const driving = new AMap.Driving({
    map: map.value,
    showTraffic: false,
    hideMarkers: true
  });

  const waypoints = validPoints
      .slice(1, -1)
      .map(item => new AMap.LngLat(item.longitude, item.latitude));

  driving.search(
      new AMap.LngLat(validPoints[0].longitude, validPoints[0].latitude),
      new AMap.LngLat(validPoints[validPoints.length - 1].longitude, validPoints[validPoints.length - 1].latitude),
      { waypoints }
  );
};

const createMarkers = async (AMap) => {
  const total = props.logisticInfo.length;

  for (const [index, item] of props.logisticInfo.entries()) {
    const config = getMarkerConfig(index, total);
    const position = await getPosition(item);

    if (!position) continue;

    const marker = new AMap.Marker({
      position: new AMap.LngLat(position.lng, position.lat),
      map: map.value,
      icon: createIcon(AMap, config),
      zIndex: index === total - 1 ? 999 : index + 1,
      extData: item
    });

    setupMarkerEvents(marker);
    markers.value.push(marker);
  }
};

const getMarkerConfig = (index, total) => {
  if (index === total-2) return iconConfig.start;
  if (index === 0) return iconConfig.end;
  if (index === total - 1) return iconConfig.car;
  return iconConfig.default;
};

const getPosition = async (item) => {
  if (item.longitude && item.latitude) {
    return { lng: item.longitude, lat: item.latitude };
  }

  try {
    const result = await new Promise(resolve =>
        geocoder.getLocation(item.location, (status, result) => resolve(result))
    );

    if (result.info === 'OK') {
      return result.geocodes[0].location;
    }
  } catch (error) {
    console.warn('地理编码失败:', item.location);
  }
  return null;
};

const createIcon = (AMap, config) => {
  return new AMap.Icon({
    image: config.url,
    size: new AMap.Size(...config.size),
    imageSize: new AMap.Size(...config.size),
    ...(config.offset && { offset: new AMap.Pixel(...config.offset) })
  });
};

const setupMarkerEvents = (marker) => {
  marker.on('mouseover', (e) => {
    const data = e.target.getExtData();
    updateTooltip({
      remarks: data.remarks,
      timeStamp: data.timeStamp
    }, marker);
  });

  marker.on('mouseout', () => {
    showTooltip.value = false;
  });
};

const focusOnCurrentPosition = () => {
  if (props.logisticInfo.length === 0) return;

  const lastItem = props.logisticInfo[props.logisticInfo.length - 1];
  if (lastItem.longitude && lastItem.latitude) {
    map.value.setCenter([lastItem.longitude, lastItem.latitude]);
    map.value.setZoom(14);
  }
};

const updateTooltip = (content, marker) => {
  showTooltip.value = true;
  tooltipContent.value = {
    remarks: content.remarks,
    timeStamp: formatTimestamp(content.timeStamp)
  };
  updateTooltipPosition(marker);
};

const updateTooltipPosition = (marker) => {
  const position = marker.getPosition();
  const pixel = map.value.lngLatToContainer(position);
  tooltipStyle.value = {
    left: `${pixel.getX()}px`,
    top: `${pixel.getY() - 40}px`
  };
};

const formatTimestamp = (timeStr) => {
  try {
    const date = new Date(timeStr);
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    }).replace(/\//g, '-');
  } catch {
    return '时间信息无效';
  }
};

onMounted(() => nextTick(initializeMap));
watch(() => [...props.logisticInfo], () => nextTick(initializeMap), {deep: true});
</script>

<style scoped>
.map-container {
  width: 100%;
  height: 500px;
  position: relative;
  background: #f5f5f5;
}

.custom-tooltip {
  position: absolute;
  background: #fff;
  border-radius: 6px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  padding: 12px 16px;
  min-width: 220px;
  transform: translate(-50%, calc(-100% - 20px));
  pointer-events: none;
  z-index: 9999;
  transition: opacity 0.2s;
}

.custom-tooltip::after {
  content: '';
  position: absolute;
  bottom: -10px;
  left: 50%;
  transform: translateX(-50%);
  border-width: 10px 8px 0;
  border-style: solid;
  border-color: #fff transparent transparent;
}

.tooltip-content {
  line-height: 1.6;
}

.remarks {
  color: #333;
  font-weight: 500;
  margin-bottom: 6px;
}

.timestamp {
  color: #666;
  font-size: 12px;
  opacity: 0.9;
}

@keyframes car-pulse {
  0% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-5px);
  }
  100% {
    transform: translateY(0);
  }
}

:deep(.amap-marker:last-child) {
  animation: car-pulse 1.5s ease-in-out infinite;
}
</style>